package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {

    private Configuration configuration;
    private Map<String, MappedStatement> mappedStatementMap;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
        mappedStatementMap = this.configuration.getMappedStatementMap();
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");


        List<Element> updates = rootElement.selectNodes("//update");
        updates.stream().forEach(element -> {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            String key = namespace + "." + id;
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setResultType(resultType);
            mappedStatementMap.put(key, mappedStatement);
        });

    }
}
